package com.gistone.commis.controller;

import com.gistone.commis.database.GetBySqlMapper;
import com.gistone.commis.entity.LoginLog;
import com.gistone.commis.entity.User;
import com.gistone.commis.mapper.LoginLogMapper;
import com.gistone.commis.mapper.UserMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by wangfan on 2017/5/1.
 */

@Controller
@RequestMapping("/api")
public class LoginController {


	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	@Qualifier("authenticationManager")
	AuthenticationManager authenticationManager;

	@Autowired
	LoginLogMapper loginLogMapper;
	@RequestMapping(value = "loginStatus",method = RequestMethod.GET)
	@ResponseBody
	public LoginStatus getStatus() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null && !auth.getName().equals("anonymousUser") && auth.isAuthenticated()) {
			return new LoginStatus(true, auth.getName(),"已经登录");
		} else {
			return new LoginStatus(false, null,"未登录");
		}
	}

	@RequestMapping(value = "login",method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public LoginStatus login(@RequestParam("username") String username,
							 @RequestParam("password") String password,
							HttpServletRequest request) {
		logger.info("登录");

		if(!checkValidateCode(request)){
			logger.info("验证码错误");
			return new LoginStatus(false, null,"验证码错误！");
		}
		logger.info("登入用户名为："+username);
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
		User details = new User(username);
		token.setDetails(details);

		try {
			Authentication auth = authenticationManager.authenticate(token);
			SecurityContextHolder.getContext().setAuthentication(auth);
			logger.info("登入用户名为："+username+"成功登录系统");

			HttpSession httpSession = request.getSession();
			User user = userMapper.findUserByUserName(username);
			httpSession.setAttribute("userInfo", user);
			System.out.println(user.getRoles().get(0).toString());

			LoginLog loginLog = new LoginLog();
			loginLog.setLoginTime(new Date());
			loginLog.setUserId(user.getUserId());
			if(loginLogMapper.insert(loginLog)>0){
				logger.info("登录日志保存成功，登录用户详细信息为："+user.toString());
				return new LoginStatus(auth.isAuthenticated(), auth.getName(),"登录成功");
			}else{
				return new LoginStatus(false, null,"保存日志失败");
			}

		} catch (Exception e) {
			System.out.println("fail");
			return new LoginStatus(false, null,"用户名或密码错误");
		}
	}

	public class LoginStatus {

		private final boolean loggedIn;
		private final String username;
		private  final  String msg;

		public LoginStatus(boolean loggedIn, String username,String msg) {
			this.loggedIn = loggedIn;
			this.username = username;
			this.msg=msg;
		}

		public boolean isLoggedIn() {
			return loggedIn;
		}

		public String getUsername() {
			return username;
		}

		public String getMsg() {
			return msg;
		}
	}


	@Autowired
	private GetBySqlMapper getBySqlMapper;

	@Autowired
	private UserMapper userMapper;







	/**
	 * 验证码判断
	 * @param request
	 * @return
	 */
	protected boolean checkValidateCode(HttpServletRequest request) {
		String result_verifyCode = request.getSession().getAttribute("randomString")
				.toString().toUpperCase(); // 获取存于session的验证值
		// request.getSession().setAttribute("verifyResult", null);
		String user_verifyCode = request.getParameter("verify");// 获取用户输入验证码
		if (null == user_verifyCode || !result_verifyCode.equalsIgnoreCase(user_verifyCode)) {
			return false;
		}
		return true;
	}







	/** 
	 *登陆查询 
	 * @throws IOException 
	 */
	@RequestMapping("select.do")
	public void select(HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		String user_name = request.getParameter("username");
		String sql = " select * from tb_user where" + " user_name = " + "'" + user_name + "'";
		//把sql丢进去获取数据   放到blz_List对象中
		List<Map> blz_List = this.getBySqlMapper.findRecords(sql);
		
		if(blz_List.size()>0){
			JSONArray jsa=new JSONArray();
			for(int i =0;i<blz_List.size();i++){
				//放到map中 以便于根据key值获取到相应的value值
				Map blz_map=blz_List.get(i);
				JSONObject blz_val = new JSONObject();
				//根据map中的key获取值并放到object中
				blz_val.put("user_name","".equals(blz_map.get("user_name")) || blz_map.get("user_name") == null ? "" : blz_map.get("user_name").toString());
				blz_val.put("userId", "".equals(blz_map.get("user_id")) || blz_map.get("user_id") == null ? "" : blz_map.get("user_id").toString());
				blz_val.put("user_pwd", "".equals(blz_map.get("user_pwd")) || blz_map.get("user_pwd") == null ? "" : blz_map.get("user_pwd").toString());
				blz_val.put("real_name", "".equals(blz_map.get("real_name")) || blz_map.get("real_name") == null ? "" : blz_map.get("real_name").toString());
				blz_val.put("depart_id", "".equals(blz_map.get("depart_id")) || blz_map.get("depart_id") == null ? "" : blz_map.get("depart_id").toString());
				blz_val.put("community_id", "".equals(blz_map.get("community_id")) || blz_map.get("community_id") == null ? "" : blz_map.get("community_id").toString());
				jsa.add(blz_val);
			}
			
			JSONObject blz_result= new JSONObject();
			blz_result.put("data", jsa);
			//获取session 将获取到的值放到session中
			HttpSession session = request.getSession(); 
			session.setAttribute("userInfo", jsa);
			
			response.getWriter().write("1");
			
		}else{
			JSONObject blz_result = new JSONObject();
			
			response.getWriter().write("0");
		}
	}
		/** 
		 *用户新增
		 * 
		 */
		@RequestMapping("insert.do")
		public void loginInsert(HttpServletRequest request,HttpServletResponse respons) {
			
			
			String sql = "insert into tb_user(user_id,user_name,user_pwd,real_name,depart_id,community_id) "
					                + "values('00033','zhangsan','aaaa','张三','00033','33')";

			int insertCount = this.getBySqlMapper.insert(sql);

	}
		/**
		 * 删除
		 */
		@RequestMapping("delete.do")
		public void loginDelete (HttpServletRequest request,HttpServletResponse respons){
			
			String sql = "DELETE FROM tb_user WHERE user_id = 1";
			
			int delCount = this.getBySqlMapper.delete(sql);
			
		}
		
		/**
		 * 修改
		 */
		@RequestMapping("uptate.do")
		public void loginUpdate(HttpServletRequest request,HttpServletResponse respons){
			
			String sql = "UPDATE tb_user SET real_name='李四' WHERE user_id = 3";
			
			int updateCount =this.getBySqlMapper.update(sql);
		}
		
}


